package com.taiyi.renaissancemall.adapter.baseadapter.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.RoundedCornersTransformation;
import com.taiyi.renaissancemall.Utils.Utils;
import com.taiyi.renaissancemall.adapter.baseadapter.CommonAdapter;
import com.taiyi.renaissancemall.base.MyApp;

public class ViewHolder extends RecyclerView.ViewHolder {
    private SparseArray<View> mViews;
    private View mConvertView;
    private Context mContext;
    private RequestOptions requestOptions = new RequestOptions();

    public ViewHolder(Context context, View itemView) {
        super(itemView);
        mContext = context.getApplicationContext();
        mConvertView = itemView;
        mViews = new SparseArray<>();
    }


    public static ViewHolder createViewHolder(Context context, View itemView) {
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    public static ViewHolder createViewHolder(Context context,
                                              ViewGroup parent, int layoutId) {
        View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    /**
     * 通过viewId获取控件
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }


    /****以下为辅助方法*****/

    /**
     * 设置TextView的值
     *
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setText(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public void setRecyclerViewGrid(int viewId, CommonAdapter adapter, int span) {
        RecyclerView recyclerView = getView(viewId);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MyApp.getInstance(), span);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
    }

    public void setRecyclerViewLinear(int viewId, CommonAdapter adapter, int span) {
        RecyclerView recyclerView = getView(viewId);
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(MyApp.getInstance());
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
    }


    public void setSelected(int viewId, boolean isSelected) {
        TextView tv = getView(viewId);
        tv.setSelected(isSelected);
    }

    public ViewHolder setImageResource(int viewId, int resId) {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    public ViewHolder setTextSize(int viewId, float sp) {
        TextView view = getView(viewId);
        view.setTextSize(sp);
        return this;
    }

    public static float sp2px(float sp) {
        DisplayMetrics displayMetrics = MyApp.getInstance().getResources().getDisplayMetrics();
        float v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, displayMetrics);
        return v;
    }

    public ViewHolder setNetworkImage(int viewId, String url) {
        ImageView view = getView(viewId);
        requestOptions.skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.mipmap.ic_launcher_foreground).dontAnimate();
        Glide.with(mContext).load(url).apply(requestOptions).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                if (resource != null) {
                    view.setImageDrawable(resource);
                }
            }
        });
        return this;
    }

    public ViewHolder setNetworkImageOne(int viewId, String url) {
        ImageView view = getView(viewId);
        // 圆角图片 new RoundedCornersTransformation 参数为 ：半径 , 外边距 , 圆角方向(ALL,BOTTOM,TOP,RIGHT,LEFT,BOTTOM_LEFT等等)
        //顶部左边圆角
        RoundedCornersTransformation transformation = new RoundedCornersTransformation
                (22, 0, RoundedCornersTransformation.CornerType.TOP_LEFT);
        //顶部右边圆角
        RoundedCornersTransformation transformation1 = new RoundedCornersTransformation
                (22, 0, RoundedCornersTransformation.CornerType.TOP_RIGHT);
        //顶部右边圆角
        RoundedCornersTransformation transformation2 = new RoundedCornersTransformation
                (0, 0, RoundedCornersTransformation.CornerType.TOP_RIGHT);
        //顶部右边圆角
        RoundedCornersTransformation transformation3 = new RoundedCornersTransformation
                (0, 0, RoundedCornersTransformation.CornerType.TOP_RIGHT);
        //组合各种Transformation,
        MultiTransformation<Bitmap> mation = new MultiTransformation<>
                //Glide设置圆角图片后设置ImageVIew的scanType="centerCrop"无效解决办法,将new CenterCrop()添加至此
                (new CenterCrop(), transformation, transformation1, transformation2, transformation3);
//
        Glide.with(mContext)
                .load(url)
                //切圆形
                .apply(RequestOptions.bitmapTransform(mation))
                .into(view);
//        requestOptions.skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.mipmap.ic_launcher_foreground).dontAnimate();
//        Glide.with(mContext).load(url).apply(requestOptions).into(new SimpleTarget<Drawable>() {
//            @Override
//            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                if (resource != null) {
//                    view.setImageDrawable(resource);
//                }
//            }
//        });
        return this;
    }

    public ViewHolder setNetworkCircleImage(int viewId, String url) {
        ImageView view = getView(viewId);
        RoundedCorners roundedCorners = new RoundedCorners(50);
        RequestOptions transform = new RequestOptions().skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.mipmap.ic_launcher_foreground).transform(roundedCorners).dontAnimate();
        Glide.with(mContext).load(url).apply(transform).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                if (resource != null) {
                    view.setImageDrawable(resource);
                }
            }
        });
        return this;
    }

    RequestOptions transform = new RequestOptions().skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate();

    public ViewHolder loadCircleImage(int viewId, String url) {
        ImageView view = getView(viewId);

        Glide.with(mContext).load(url).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(view);
        return this;
    }

    public ViewHolder loadCircleImageN(int viewId, String url) {
        ImageView view = getView(viewId);

        Glide.with(mContext.getApplicationContext()).load(url).apply(RequestOptions.bitmapTransform(new CircleCrop())).apply(transform).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                if (resource != null) {
                    view.setImageDrawable(resource);
                }
            }
        });
        return this;
    }


    public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
        ImageView view = getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }

    public ViewHolder setImageDrawable(int viewId, Drawable drawable) {
        ImageView view = getView(viewId);
        view.setImageDrawable(drawable);
        return this;
    }

    public ViewHolder setBackgroundColor(int viewId, int color) {
        View view = getView(viewId);
        view.setBackgroundColor(color);
        return this;
    }

    public ViewHolder setBackgroundRes(int viewId, int backgroundRes) {
        View view = getView(viewId);
        view.setBackgroundResource(backgroundRes);
        return this;
    }

    public ViewHolder setTextColor(int viewId, int textColor) {
        TextView view = getView(viewId);
        view.setTextColor(textColor);
        return this;
    }

    public ViewHolder setTextColorRes(int viewId, int textColorRes) {
        TextView view = getView(viewId);
        view.setTextColor(mContext.getResources().getColor(textColorRes));
        return this;
    }

    @SuppressLint("NewApi")
    public ViewHolder setAlpha(int viewId, float value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getView(viewId).setAlpha(value);
        } else {
            // Pre-honeycomb hack to set Alpha value
            AlphaAnimation alpha = new AlphaAnimation(value, value);
            alpha.setDuration(0);
            alpha.setFillAfter(true);
            getView(viewId).startAnimation(alpha);
        }
        return this;
    }

    public ViewHolder setVisible(int viewId, boolean visible) {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }

    public ViewHolder setVisible1(int viewId, boolean visible) {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
        return this;
    }

    public ViewHolder linkify(int viewId) {
        TextView view = getView(viewId);
        Linkify.addLinks(view, Linkify.ALL);
        return this;
    }

    public ViewHolder setTypeface(Typeface typeface, int... viewIds) {
        for (int viewId : viewIds) {
            TextView view = getView(viewId);
            view.setTypeface(typeface);
            view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress) {
        ProgressBar view = getView(viewId);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress, int max) {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setMax(int viewId, int max) {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating) {
        RatingBar view = getView(viewId);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating, int max) {
        RatingBar view = getView(viewId);
        view.setMax(max);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setTag(int viewId, Object tag) {
        View view = getView(viewId);
        view.setTag(tag);
        return this;
    }

    public ViewHolder setTag(int viewId, int key, Object tag) {
        View view = getView(viewId);
        view.setTag(key, tag);
        return this;
    }

    public ViewHolder setChecked(int viewId, boolean checked) {
        Checkable view = (Checkable) getView(viewId);
        view.setChecked(checked);
        return this;
    }

    /**
     * 关于事件的
     */
    public ViewHolder setOnClickListener(int viewId,
                                         View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public ViewHolder setOnTouchListener(int viewId,
                                         View.OnTouchListener listener) {
        View view = getView(viewId);
        view.setOnTouchListener(listener);
        return this;
    }

    public ViewHolder setOnLongClickListener(int viewId,
                                             View.OnLongClickListener listener) {
        View view = getView(viewId);
        view.setOnLongClickListener(listener);
        return this;
    }


}
